package com.java.basis.thread.n3;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wangning
 * @create 2022-01-24 10:56
 */
@Slf4j(topic = "c.TestReentrantLock02")
public class TestReentrantLock02 {
	private static ReentrantLock lock = new ReentrantLock();

	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new Thread(() -> {
			try {
				log.debug("尝试获得锁");
				//如果没有竞争那么此方法就会获取 lock 对象锁
				//如果有竞争就进入阻塞队列。可以被其它线程用 interrupt 方法打断，不要再等了
				//如果使用lock.lock();，方法不能打断
				lock.lockInterruptibly();
			} catch (InterruptedException e) {
				e.printStackTrace();
				log.debug("没有获得锁");
				return;
			}

			try {
				log.debug("获得到锁");
			} finally {
				lock.unlock();
			}

		});
		lock.lock();
		t1.start();

		Thread.sleep(1000);
		log.debug("打断t1");
		t1.interrupt();

	}




}
